<script lang="ts" setup>
import { ref } from "vue";
import { RequestDTO } from "@/dto/general";

// 打开接收消息的端口
const startListeningPort = () => {
  browser.runtime.onConnect.addListener((port) => {
    port.onMessage.addListener((message: RequestDTO, port) => {
      if (message.to == "popup") {
        if (port.name == "content") {
          console.log("popup -  from content" + JSON.stringify(message));
        }
        if (port.name == "background") {
          console.log("popup -  from background" + JSON.stringify(message));
        }
      }
    });
  });
};


const sendToContent = (name:string) => {
  var message: RequestDTO = new RequestDTO(
    name,
    "content",
    { num: 10 },
    "getMessage"
  );
  browser.tabs.query({"active": true}).then((tabs) => {
    if(tabs.length == 0 || tabs[0].id == undefined){
      console.log("error - no tabs")
      return 
    }
    browser.tabs.sendMessage(tabs[0].id, message)
  })
}

defineProps({
  msg: String,
});

const getMessage = (name: string) => {
  var message: RequestDTO = new RequestDTO(
    name,
    "content",
    { num: 10 },
    "getMessage"
  );
  var port = browser.runtime.connect({ name: name });
  port.postMessage(message);
  port.disconnect();
};

onMounted(() => {
  startListeningPort();
});


</script>

<template>
  <div class="card">
  </div>
  <Button type="success" @click="sendToContent('popup')">获取消息</Button>
</template>

<style scoped>
.read-the-docs {
  color: #888;
}
</style>
